<!--
 * @Author: Bobby
 * @Date: 2021-12-30 10:01:42
 * @LastEditTime: 2023-09-13 11:54:09
 * @LastEditors: 甯左龙 1173405584@qq.com
 * @Description:
 * @FilePath: \wms-v2\src\ve\elements\form\uiInput\uiInput.vue
 * CIMC-V2
-->
<template>
  <div class="w-full">
    <el-input-number
      :ref="moduleId"
      v-model="formDataItem[formDataKey]"
      clearable
      :controls="info.extension.controls.value"
      :disabled="disabled"
      :max="isFiniteFunc(info.extension.maxVal.value) ? info.extension.maxVal.value : 100000000000000000000"
      :min="isFiniteFunc(info.extension.minVal.value) ? info.extension.minVal.value : -100000000000000000000"
      :precision="isFiniteFunc(info.extension.precision.value) ? info.extension.precision.value : 10"
      size="mini"
      :step="stepValue"
      @change="valueChange"
      @focus="handleFocus"
      @keyup.enter="nextModuleFocus"
      @keydown="handlerKeyDown"
      @mousewheel.prevent
    />
  </div>
</template>
<script>
  import { defineComponent } from 'vue'
  import isFinite from 'lodash/isFinite'
  import isInteger from 'lodash/isInteger'
  import trim from 'lodash/trim'
  import { tableFormItemMixin } from '@ve/mixin'
  import { ElMessage } from 'element-plus'
  import { componentId } from '@/utils/unique'
  // import { getModelByModelTree } from '@ve/utils/utils'
  export default defineComponent({
    name: 'UiTableNumberInput',
    components: {},
    mixins: [tableFormItemMixin],
    props: {
      rowData: {
        type: Object,
        default: () => {
          return {}
        },
      },
      editFormItem: {
        type: String,
        default: '',
      },
    },
    emits: ['editFormItemChange'],
    data() {
      return {
        moduleId: '',
        stepValue: 1,
        changeIndex: 0,
      }
    },
    computed: {
      formModuleData() {
        return this.formModule.data && this.formModule.data.formData
      },
      anIntegerModel() {
        return this.info.extension.anInteger.value
      },
      arithmeticOperation() {
        return this.info.extension.arithmeticOperation && this.info.extension.arithmeticOperation.value
      },
    },
    watch: {
      rowData: {
        deep: true,
        handler(newval) {
          if (this.anIntegerModel) {
            console.log('触发整数倍！！！！', this.anIntegerModel, newval[this.anIntegerModel])
            if (this.info.extension.nullValueControl.value && !newval[this.anIntegerModel]) {
              // 如果配置了空值不控制并且值为空 则不进行判断
              console.log('kzmk')
              this.stepValue = 1
            } else {
              // 判断整数倍条件
              const result = this.formDataItem[this.formDataKey] / newval[this.anIntegerModel]
              if (!isInteger(result)) {
                // 如果不是整数倍 则将值置为空
                this.$nextTick(() => {
                  this.formDataItem[this.formDataKey] = 0
                })
              }
              // 将 step 置为绑定值
              this.stepValue = newval[this.anIntegerModel]
            }
          }
          // else if (this.arithmeticOperation) {
          //   console.log('触发算数计算！！！！')
          //   // 如果有配置数值计算 则进行计算
          //   this.formDataItem[this.formDataKey] = this.arithmeticFunc(this.arithmeticOperation)
          // }
        },
      },
      editFormItem: {
        handler(newval) {
          if (this.arithmeticOperation) {
            console.log('触发算数计算！！！！', this.info.extension.precision)
            // 如果有配置数值计算 则进行计算
            let arithmeticResult = this.arithmeticFunc(this.arithmeticOperation, newval.split('&')[0])
            // 如果计算没有结果 则不做值改变
            if (arithmeticResult === false) return
            // 做小数位处理
            if (this.isFiniteFunc(this.info.extension.precision.value)) {
              const powValue = Math.pow(10, this.info.extension.precision.value)
              if (this.info.extension.getPrecisionType && this.info.extension.getPrecisionType.value) {
                const getPrecisionType = this.info.extension.getPrecisionType.value
                if (getPrecisionType === 'round') {
                  // 采取四舍五入处理方式
                  arithmeticResult = Math.round(arithmeticResult * powValue) / powValue
                } else if (getPrecisionType === 'advance') {
                  // 采取进一的处理方式
                  arithmeticResult = Math.ceil(arithmeticResult * powValue) / powValue
                } else if (getPrecisionType === 'discard') {
                  // 采取丢弃的处理方式
                  arithmeticResult = Math.floor(arithmeticResult * powValue) / powValue
                }
              } else {
                // 默认采取四舍五入处理方式
                arithmeticResult = Math.round(arithmeticResult * powValue) / powValue
              }
            }

            this.formDataItem[this.formDataKey] = arithmeticResult
          }
        },
      },
    },
    created() {
      // 生成组件ID
      this.moduleId = `uiTableNumberInput_${componentId(6)}`
      this.stepValue = this.isFiniteFunc(this.info.extension.step.value) ? this.info.extension.step.value : 1
    },
    mounted() {
      // 添加组件实例至状态管理器存储
      if (!this.disabled)
        this.$store.dispatch('tableFormItem/setTableFormItemList', {
          id: this.moduleId,
          ref: this.$refs[this.moduleId],
        })
    },
    methods: {
      isFiniteFunc(val) {
        return isFinite(val)
      },
      arithmeticFunc(expression, newval) {
        // 对获取到的消息内容做变量拆分 -- #{}符号包裹内容视为变量
        const staticList = expression.split(/#{.*?}/gi)
        const variableList = expression.match(/#{(.+?)\}/g)
        let arithmeticStr = ''
        let resultValue = 0
        // 如果当前配置的计算式变量中不包含当前改变的值 则不进行计算
        if (variableList.indexOf(newval) === -1) return false
        if (variableList && variableList.length) {
          // 如果有配置变量 则先获取变量值
          variableList.forEach((variableItem, index) => {
            let variableContent = ''
            variableItem = trim(variableItem.slice(2, -1))
            if (variableItem.indexOf('->') !== -1) {
              const fieldList = variableItem.split('->')
              variableContent = this.rowData
              fieldList.forEach((fieldItem) => {
                // 如果没有后续值则不继续往下取值
                if (variableContent[trim(fieldItem)] === undefined) return
                variableContent = variableContent[trim(fieldItem)]
              })
            } else {
              variableContent = this.rowData[variableItem]
            }
            staticList.splice(index * 2 + 1, 0, variableContent)
          })
          arithmeticStr = staticList.join('')
        }
        console.log('arithmeticStr 00000000000000000 ', arithmeticStr, newval)
        try {
          // 执行字符串
          resultValue = Function('"use strict";return (' + arithmeticStr + ')')()
        } catch (error) {
          console.log('error', error)
          ElMessage({
            showClose: true,
            message: '算数运算 - 算式执行错误！',
            type: 'error',
          })
          resultValue = 0
        }
        return resultValue
      },
      valueChange() {
        // 改变当前修改项
        this.changeIndex++
        this.$emit('editFormItemChange', `${this.formDataKey}&${this.changeIndex}`)
      },
      handleFocus() {
        // console.log('选中了', this.$refs[this.moduleId].$el)
        // console.log(this.$refs[this.moduleId].$el.getElementsByTagName('input')[0])
        if (this.$refs[this.moduleId] && this.$refs[this.moduleId].$el && this.$refs[this.moduleId].$el.getElementsByTagName('input')[0]) {
          this.$refs[this.moduleId].$el.getElementsByTagName('input')[0].select()
        }
      },
      handlerKeyDown(event) {
        // 保存的时候先调用失焦保存输入的值
        if (event.ctrlKey && event.keyCode === 83) {
          this.$refs[this.moduleId].$el.getElementsByTagName('input')[0].blur()
        }
      },
    },
  })
</script>

<style lang="scss" scoped>
  .el-input-number {
    width: 100%;
  }
  :deep() .el-input-number--mini .el-input-number__decrease,
  :deep() .el-input-number--mini .el-input-number__increase {
    height: 24px;
  }

  :deep() [type='number'] {
    border: 1px solid #dcdfe6;
  }
</style>
